<template>
  <div class="page-content">
    <el-row>
      <el-col :xs="24" :sm="12" :lg="6">
        <el-input v-model="searchQuery" placeholder="角色名称" @keyup.enter="handleSearch"></el-input>
      </el-col>
      <div style="width: 12px"></div>
      <el-col :xs="24" :sm="12" :lg="6" class="el-col2">
        <el-button v-ripple @click="handleSearch">搜索</el-button>
        <el-button @click="showDialog('add')" v-ripple>新增角色</el-button>
      </el-col>
    </el-row>

    <art-table :data="tableData" v-loading="loading" :pagination="pagination" @pagination-change="handlePageChange">
      <template #default>
        <el-table-column label="角色名称" prop="label" />
        <el-table-column label="角色标识" prop="alias" />
        <el-table-column label="描述" prop="remark" />
        <el-table-column label="菜单权限" align="center" width="120">
          <template #default="scope">
            <el-tooltip 
              effect="dark" 
              placement="top" 
              :content="getMenuToolTip(scope.row)"
            >
              <el-tag type="success" size="small">
                {{ (scope.row.menus?.length || 0) + ' 个权限' }}
              </el-tag>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'primary' : 'info'">
              {{ scope.row.status === 1 ? '启用' : '禁用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间">
          <template #default="scope">
            {{ formatDate(scope.row.created_at || scope.row.date) }}
          </template>
        </el-table-column>
        <el-table-column fixed="right" label="操作" width="100px">
          <template #default="scope">
            <el-row>
              <button-more
                :list="[
                  { key: 'permission', label: '菜单权限' },
                  { key: 'edit', label: '编辑角色' },
                  { key: 'delete', label: '删除角色' }
                ]"
                @click="buttonMoreClick($event, scope.row)"
              />
            </el-row>
          </template>
        </el-table-column>
      </template>
    </art-table>

    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增角色' : '编辑角色'"
      width="30%"
    >
      <el-form ref="formRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="角色名称" prop="label">
          <el-input v-model="form.label" />
        </el-form-item>
        <el-form-item label="角色标识" prop="alias">
          <el-input v-model="form.alias" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" :active-value="1" :inactive-value="0" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit(formRef)" :loading="submitLoading">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <el-dialog v-model="permissionDialog" title="菜单权限" width="40%" top="5vh">
      <div :style="{ maxHeight: '500px', overflowY: 'auto' }">
        <el-alert
          v-if="menuList.length === 0"
          type="info"
          title="正在加载菜单数据..."
          :closable="false"
          show-icon
        />
        <el-alert
          v-else-if="selectedMenuIds.length === 0"
          type="warning"
          title="当前角色暂无菜单权限"
          :closable="false"
          show-icon
        />
        <div v-if="menuList.length > 0" class="menu-tree-actions">
          <el-button size="small" @click="selectAllMenus" type="primary" plain>全选</el-button>
          <el-button size="small" @click="deselectAllMenus">清空</el-button>
        </div>
        <el-tree
          ref="menuTree"
          :data="menuList"
          show-checkbox
          node-key="id"
          :default-checked-keys="selectedMenuIds"
          :props="defaultProps"
          :default-expand-all="menuList.length < 50"
        />
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="permissionDialog = false">取消</el-button>
          <el-button type="primary" @click="saveMenuPermissions" :loading="menuPermissionLoading">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
  import { ButtonMoreItem } from '@/components/Form/ButtonMore.vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import type { FormInstance, FormRules } from 'element-plus'
  import { formatMenuTitle } from '@/utils/menu'
  import { onMounted, ref, reactive, nextTick } from 'vue'
  import { roleService } from '@/api/roleApi'

  // 状态变量
  const dialogVisible = ref(false)
  const permissionDialog = ref(false)
  const dialogType = ref('add')
  const searchQuery = ref('')
  const loading = ref(false)
  const submitLoading = ref(false)
  const menuPermissionLoading = ref(false)
  const selectedMenuIds = ref<number[]>([])
  const currentRoleId = ref<number | null>(null)
  const menuTree = ref(null)
  const formRef = ref<FormInstance>()
  const menuList = ref([])
  const tableData = ref([])
  
  // 分页配置
  const pagination = reactive({
    currentPage: 1,
    pageSize: 20,
    total: 0
  })

  // 表单数据
  const form = reactive({
    id: null,
    label: '',
    alias: '',
    remark: '',
    sort: 10,
    status: 1
  })

  // 表单验证规则
  const rules = reactive<FormRules>({
    label: [
      { required: true, message: '请输入角色名称', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    alias: [
      { required: true, message: '请输入角色标识', trigger: 'blur' },
      { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
    ],
    remark: [{ required: true, message: '请输入角色描述', trigger: 'blur' }]
  })

  // 树形控件配置
  const defaultProps = {
    children: 'children',
    label: (data: any) => {
      if (data.meta?.title) {
        return formatMenuTitle(data.meta.title)
      }
      return data.name || '未命名菜单'
    }
  }

  // 页面初始化时获取角色列表
  onMounted(async () => {
    await fetchRoleList()
  })

  // 获取角色列表
  const fetchRoleList = async () => {
    loading.value = true
    try {
      // 构建查询参数
      const searchParams = {}
      if (searchQuery.value.trim()) {
        searchParams['label'] = searchQuery.value.trim()
      }

      const result = await roleService.getRoleList(
        pagination.currentPage,
        pagination.pageSize,
        searchParams
      )

      tableData.value = result.list || []
      pagination.total = result.total || 0
    } catch (error) {
      console.error('获取角色列表失败:', error)
    } finally {
      loading.value = false
    }
  }

  // 搜索角色
  const handleSearch = () => {
    pagination.currentPage = 1 // 重置为第一页
    fetchRoleList()
  }

  // 分页变化处理
  const handlePageChange = (page: any) => {
    pagination.currentPage = page.currentPage
    pagination.pageSize = page.pageSize
    fetchRoleList()
  }

  // 显示添加/编辑对话框
  const showDialog = (type: string, row?: any) => {
    dialogVisible.value = true
    dialogType.value = type

    // 重置表单
    Object.assign(form, {
      id: null,
      label: '',
      alias: '',
      remark: '',
      sort: 10,
      status: 1
    })

    if (type === 'edit' && row) {
      nextTick(() => {
        // 编辑模式，回显数据
      form.id = row.id
        form.label = row.label || ''
        form.alias = row.alias || ''
        form.remark = row.remark || row.des || ''
        form.sort = row.sort || 10
        form.status = row.status === undefined ? 1 : row.status
      })
    }
  }

  // 按钮操作
  const buttonMoreClick = (item: ButtonMoreItem, row: any) => {
    if (item.key === 'permission') {
      showPermissionDialog(row)
    } else if (item.key === 'edit') {
      showDialog('edit', row)
    } else if (item.key === 'delete') {
      deleteRole(row)
    }
  }

  // 显示权限对话框
  const showPermissionDialog = async (row: any) => {
    if (!row || !row.id) {
      ElMessage.warning('角色数据不完整，无法设置权限')
      return
    }

    currentRoleId.value = row.id
    menuPermissionLoading.value = true
    permissionDialog.value = true
    
    try {
      // 获取所有菜单
      const allMenus = await roleService.getAllMenus()
      menuList.value = allMenus || []

      // 设置当前角色已选菜单
      // 从角色的menus数组中提取菜单ID
      const roleMenus = row.menus || []
      selectedMenuIds.value = roleMenus.map((menu: any) => menu.id || menu)
      
      console.log('当前角色菜单权限:', {
        roleId: row.id,
        roleName: row.label,
        menuIds: selectedMenuIds.value
      })
      
      // 等待DOM更新，然后设置选中状态
      nextTick(() => {
        if (menuTree.value) {
          menuTree.value.setCheckedKeys(selectedMenuIds.value)
        }
      })
    } catch (error) {
      console.error('获取菜单列表失败:', error)
      ElMessage.error('获取菜单列表失败')
    } finally {
      menuPermissionLoading.value = false
    }
  }

  // 保存菜单权限
  const saveMenuPermissions = async () => {
    if (!currentRoleId.value || !menuTree.value) {
      ElMessage.warning('数据不完整，无法保存权限')
      return
    }

    // 获取选中的菜单ID
    const checkedNodes = menuTree.value.getCheckedNodes()
    const checkedKeys = checkedNodes.map((node: any) => node.id)
    
    // 获取半选中的菜单ID（父节点）
    const halfCheckedNodes = menuTree.value.getHalfCheckedNodes()
    const halfCheckedKeys = halfCheckedNodes.map((node: any) => node.id)
    
    // 合并完全选中和半选中的ID
    const allSelectedKeys = [...checkedKeys, ...halfCheckedKeys]
    
    console.log('准备保存菜单权限:', {
      roleId: currentRoleId.value,
      checkedMenus: checkedKeys.length,
      halfCheckedMenus: halfCheckedKeys.length,
      totalMenus: allSelectedKeys.length
    })
    
    menuPermissionLoading.value = true
    try {
      await roleService.updateRoleMenuPermissions(currentRoleId.value, allSelectedKeys)
      
      // 更新当前表格中该角色的菜单数据
      const roleIndex = tableData.value.findIndex(role => role.id === currentRoleId.value)
      if (roleIndex !== -1) {
        // 创建简单的菜单对象数组，模拟后端返回的菜单数据结构
        const updatedMenus = allSelectedKeys.map(id => ({ id }))
        tableData.value[roleIndex].menus = updatedMenus
      }
      
      permissionDialog.value = false
      ElMessage.success(`菜单权限更新成功，共设置了 ${allSelectedKeys.length} 个菜单权限`)
    } catch (error) {
      console.error('保存菜单权限失败:', error)
      ElMessage.error('保存菜单权限失败，请重试')
    } finally {
      menuPermissionLoading.value = false
    }
  }

  // 删除角色
  const deleteRole = (row: any) => {
    if (!row || !row.id) {
      ElMessage.warning('无法删除，缺少角色ID')
      return
    }
    
    ElMessageBox.confirm('确定删除该角色吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'error'
    }).then(async () => {
      loading.value = true
      try {
        await roleService.deleteRoles([row.id])
        await fetchRoleList()
      } catch (error) {
        console.error('删除角色失败:', error)
      } finally {
        loading.value = false
      }
    }).catch(() => {
      // 用户取消删除，不做处理
    })
  }

  // 提交表单
  const handleSubmit = async (formEl: FormInstance | undefined) => {
    if (!formEl) return

    await formEl.validate(async (valid) => {
      if (valid) {
        submitLoading.value = true
        try {
          // 构建提交数据
          const roleData = {
            alias: form.alias,
            label: form.label,
            remark: form.remark,
            sort: form.sort,
            status: form.status
          }

          if (dialogType.value === 'edit' && form.id) {
            // 编辑模式
            await roleService.updateRole({ ...roleData, id: form.id })
          } else {
            // 添加模式
            await roleService.addRole(roleData)
          }

        dialogVisible.value = false
          await fetchRoleList()
        } catch (error) {
          console.error(`${dialogType.value === 'add' ? '新增' : '修改'}角色失败:`, error)
        } finally {
          submitLoading.value = false
        }
      }
    })
  }

  // 格式化日期
  const formatDate = (date: string) => {
    if (!date) return '-'
    
    try {
    return new Date(date)
      .toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
      .replace(/\//g, '-')
    } catch (error) {
      return date
    }
  }

  // 全选所有菜单
  const selectAllMenus = () => {
    if (!menuTree.value) return
    
    const allMenuIds = getAllMenuIds(menuList.value)
    menuTree.value.setCheckedKeys(allMenuIds)
  }

  // 清空所有选中的菜单
  const deselectAllMenus = () => {
    if (!menuTree.value) return
    menuTree.value.setCheckedKeys([])
  }

  // 递归获取所有菜单ID
  const getAllMenuIds = (menus: any[]): number[] => {
    let ids: number[] = []
    
    for (const menu of menus) {
      if (menu.id) {
        ids.push(menu.id)
      }
      
      if (menu.children && menu.children.length > 0) {
        ids = [...ids, ...getAllMenuIds(menu.children)]
      }
    }
    
    return ids
  }

  // 获取菜单权限提示文本
  const getMenuToolTip = (role: any): string => {
    const menus = role.menus || []
    
    if (menus.length === 0) {
      return '该角色暂无菜单权限'
    }
    
    // 最多显示5个菜单名称
    const displayMenus = menus.slice(0, 5)
    const menuNames = displayMenus.map((menu: any) => {
      // 尝试从meta.title或name中获取菜单名称
      if (menu.meta?.title) {
        return formatMenuTitle(menu.meta.title)
      }
      return menu.name || menu.id || '未命名菜单'
    })
    
    let tooltipText = menuNames.join('、')
    
    // 如果有更多菜单，显示省略号
    if (menus.length > 5) {
      tooltipText += `...等共 ${menus.length} 个菜单权限`
    }
    
    return tooltipText
  }
</script>

<style lang="scss" scoped>
  .page-content {
    .svg-icon {
      width: 1.8em;
      height: 1.8em;
      overflow: hidden;
      vertical-align: -8px;
      fill: currentcolor;
    }
    
    .el-col2 {
      display: flex;
      gap: 10px;
      margin-top: 12px;
      
      @media (min-width: 768px) {
        margin-top: 0;
      }
    }
  }
  
  .dialog-footer {
    padding-top: 10px;
    text-align: right;
  }

  .menu-tree-actions {
    margin: 10px 0;
    display: flex;
    gap: 10px;
    justify-content: flex-start;
  }

  :deep(.el-tree) {
    margin-top: 10px;
    border: 1px solid var(--el-border-color-light);
    border-radius: 4px;
    padding: 10px;
    background-color: var(--el-bg-color-overlay);

    .el-tree-node__content {
      height: 32px;
      
      &:hover {
        background-color: var(--el-fill-color-light);
      }
    }
  }

  :deep(.el-alert) {
    margin: 10px 0;
  }
</style>

